package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.context.UserThreadLocal;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.FamilyMemberDto;
import com.zzyl.nursing.dto.LoginVo;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.IWechatService;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.FamilyMemberVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.HashMap;


@Slf4j
@Service
public class FamilyMemberServiceImpl implements IFamilyMemberService {

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    /**
     * 登录
     *
     * @param loginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto loginRequestDto) {
        //获取openid
        String openid = wechatService.getOpenid(loginRequestDto.getCode());

        if (!StringUtils.hasText(openid)) {
            //获取openid失败
            throw new BaseException("用户不合法");
        }

        //根据openid查数据可以, 判断是否已经登录
        FamilyMember familyMember = familyMemberMapper.selectOne(new LambdaQueryWrapper<FamilyMember>().eq(FamilyMember::getOpenId, openid));
        if (ObjectUtil.isEmpty(familyMember)) {
            //未登录则添加
            String phone = wechatService.getPhone(loginRequestDto.getPhoneCode());
            familyMember = FamilyMember.builder().name("花开富贵").phone(phone).openId(openid).createTime(LocalDate.now()).build();
            familyMemberMapper.insert(familyMember);
        }
        //存在直接封装token返回
        HashMap<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", familyMember.getId());
        userInfo.put("openid",openid);

        String appletToken = tokenService.createAppletToken(userInfo);
        return LoginVo.builder().nickName(familyMember.getName()).token(appletToken).build();
    }

    /**
     * 绑定家人
     *
     * @param familyMemberDto
     */
    @Override
    public void bindElder(FamilyMemberDto familyMemberDto) {
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, familyMemberDto.getIdCard()));
        if (ObjectUtil.isEmpty(elder)) {
            throw new BaseException("老人不存在");
        }

        FamilyMemberElder familyMemberElder = FamilyMemberElder.builder()
                .elderId(elder.getId())
                .familyMemberId(UserThreadLocal.getUserId())
                .remark(familyMemberDto.getRemark())
                .build();
        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 查询我的家人列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public FamilyMemberVo selectMyFamilyList(Integer pageNum, Integer pageSize) {
        FamilyMemberVo familyMemberVo = familyMemberMapper.selectMyFamilyList();
        return familyMemberVo;
    }

    /**
     * 分页查询家人列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public TableDataInfo<FamilyMemberElderVo> selectFamilyListByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        Long userId = UserThreadLocal.getUserId();
        Page<FamilyMemberElderVo> page = familyMemberMapper.selectFamilyListByPage(userId);

        return new TableDataInfo<FamilyMemberElderVo>(page.getResult(), Math.toIntExact(page.getTotal()));
    }
}

